﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using System.Data;
using System.IO;
using NITGEN.SDK.NBioBSP;
using System.Data.SqlClient;
using System.Configuration;
//using NBioBSPCOMLib;

namespace AbhiRuchiFoods
{
    /// <summary>
    /// Interaction logic for UserControl1.xaml
    /// </summary>
    /// 

    public partial class EmployeeInformation : UserControl
    {
        string fileName,filePath;
        public static string NavigateEmpNo;
        NBioAPI m_NBioAPI;
        NBioAPI.IndexSearch m_IndexSearch;
        NBioAPI.IndexSearch.FP_INFO[] fingerPrintInfo;
        MemoryStream fingerPrint;
        byte[] fingerData;
        string fingerPrintTextData = string.Empty;

        public EmployeeInformation()
        {
            InitializeComponent();
            m_NBioAPI = new NBioAPI();
            m_IndexSearch = new NBioAPI.IndexSearch(m_NBioAPI);
            uint ret = m_IndexSearch.InitEngine();
            if (ret != NBioAPI.Error.NONE)
            {
                DisplayErrorMsg(ret);
            }

            if (EmployeeInformation.NavigateEmpNo != null)
                setControlValues();

        }

        private void setControlValues()
        {
            DataTable dtEmp = new DataTable();
            dtEmp = AbhiruchiDAL.SearchEmployeeBasedOnEmpNo(NavigateEmpNo.ToString());
            string fullname = dtEmp.Rows[0]["EmployeeName"].ToString();
            string[] name = fullname.Split(' ');
            txtFirstName.Text = name[0].ToString();
            txtLastName.Text = name[1].ToString();
            txtFatherName.Text = dtEmp.Rows[0]["FatherName"].ToString();
            picDate.Text = dtEmp.Rows[0]["DOB"].ToString();
            txtQualification.Text = dtEmp.Rows[0]["Qualification"].ToString();
            txtAddress.Text = dtEmp.Rows[0]["Address"].ToString();
            txtPhone.Text = dtEmp.Rows[0]["PhoneNo"].ToString();
            txtPersonalEmail.Text = dtEmp.Rows[0]["PersonalEmail"].ToString();
            txtCompanyEmail.Text = dtEmp.Rows[0]["CompanyEmail"].ToString();
            if (Convert.ToInt32(dtEmp.Rows[0]["IsActive"]) == 1)
                chkIsActive.IsChecked = true;
            else
                chkIsActive.IsChecked = false;
            if (dtEmp.Rows[0][13].ToString() != "")
            {
                filePath = dtEmp.Rows[0][13].ToString();
                ImageSourceConverter imgs = new ImageSourceConverter();
                imgEmp.SetValue(Image.SourceProperty, imgs.ConvertFromString(dtEmp.Rows[0][13].ToString()));
            }
            
        }

        private void ClearAllFields()
        {
            txtFirstName.Text = "";
            txtLastName.Text = "";
            picDate.Text = "";
            txtFatherName.Text = "";
            txtQualification.Text = "";
            txtAddress.Text = "";
            txtPhone.Text = "";
            txtPersonalEmail.Text = "";
            txtCompanyEmail.Text = "";
            imgEmp.Source = null;
            if (EmployeeInformation.NavigateEmpNo != null)
            {
                EmployeeInformation.NavigateEmpNo = null;
                SearchEmployeeInformation obj = new SearchEmployeeInformation();
                this.Content = obj;
            }
        }

        private bool doValidations()
        {
            if (txtFirstName.Text == "")
            {
                MessageBox.Show("Please Enter First Name", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
            if (picDate.Text == "")
            {
                MessageBox.Show("Please Select Your Date of Birth", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
            else if (picDate.Text != "")
            {
                if (DateTime.Parse(picDate.Text) > DateTime.Now)
                {
                    MessageBox.Show("Date Of Birth Cannot Be Greater Than Present Date", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }
            }
            if (txtFatherName.Text == "")
            {
                MessageBox.Show("Please Enter Your Father's Name", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
            if (txtQualification.Text == "")
            {
                MessageBox.Show("Please Enter Your Higest Qualification", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
            if (txtAddress.Text == "")
            {
                MessageBox.Show("Please Enter Your Permanent Address", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
            if (txtPhone.Text == "")
            {
                MessageBox.Show("Please Enter Your Phone No", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
            else if (txtPhone.Text != "")
            {
                bool flag = false;
                foreach (char ch in txtPhone.Text)
                {
                    if (!((ch >= 48) && (ch <= 57)))
                    {
                        flag = true;
                        break;
                    }      
                }
                if (flag)
                {
                    MessageBox.Show("You Have entered Invalid Mobile No", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }
            }
            if (txtPersonalEmail.Text == "")
            {
                MessageBox.Show("Please Enter Your Personal Email", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
            else if (txtPersonalEmail.Text != "")
            {
                if (!(Regex.Match(txtPersonalEmail.Text, @"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$").Success))
                {
                    MessageBox.Show("You Have entered Invalid Personal Email Id", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }
            }
            if (txtCompanyEmail.Text == "")
            {
                MessageBox.Show("Please Enter Your Company Email", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
            else if (txtCompanyEmail.Text != "")
            {
                if (!(Regex.Match(txtCompanyEmail.Text, @"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$").Success))
                {
                    MessageBox.Show("You Have entered Invalid Copmpany Email Id", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }
            }
            return true;

        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            ClearAllFields();
        }

        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            int active;
            if (chkIsActive.IsChecked == true)
                active = 1;
            else
                active = 0;


            if (doValidations() == true)
            {
                if (NavigateEmpNo == null)
                {
                    AbhiruchiDAL.SetPermanentEmployeeInformation(txtFirstName.Text, txtLastName.Text, txtFatherName.Text, picDate.Text.ToString(),
                        txtQualification.Text, null, txtPhone.Text, txtPersonalEmail.Text, txtCompanyEmail.Text, txtAddress.Text, active, 1, filePath);

                    if ((fingerPrintInfo != null) && (fingerData != null) && (fingerPrintTextData != null))//fingerPrints are Registerd.
                    {
                        foreach (NBioAPI.IndexSearch.FP_INFO sampleInfo in fingerPrintInfo)
                        {
                            AbhiruchiDAL.setEmployeeBiometricInformation(sampleInfo.ID.ToString(), sampleInfo.FingerID.ToString(), sampleInfo.SampleNumber.ToString(), fingerData, fingerPrintTextData);
                        }
                    }

                    ClearAllFields();
                    MessageBox.Show("Permanent Employee Profile Saved Successfully", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    AbhiruchiDAL.ModifyPermanentEmployeeInformation(NavigateEmpNo, txtFirstName.Text, txtLastName.Text, txtFatherName.Text, picDate.Text.ToString(),
                        txtQualification.Text, null, txtPhone.Text, txtPersonalEmail.Text, txtCompanyEmail.Text, txtAddress.Text, active, 1, filePath);
                    if ((fingerPrintInfo != null) && (fingerData != null) && (fingerPrintTextData != null))//fingerPrints are Again Registerd.
                    {
                        foreach (NBioAPI.IndexSearch.FP_INFO sampleInfo in fingerPrintInfo)
                        {
                            AbhiruchiDAL.ModifyEmployeeBiometricInformation(sampleInfo.ID.ToString(), sampleInfo.FingerID.ToString(), sampleInfo.SampleNumber.ToString(), fingerData, fingerPrintTextData);
                        }
                    }
                    ClearAllFields();
                    SearchEmployeeInformation p = new SearchEmployeeInformation();
                    EmployeeInformation.NavigateEmpNo = null;
                    this.Content = p;
                    MessageBox.Show("Permanent Employee Profile Modified Successfully", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
        }

        private void btnUpload_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog od = new System.Windows.Forms.OpenFileDialog();
            od.ShowDialog();
            ImageSourceConverter imgs = new ImageSourceConverter();
            imgEmp.SetValue(Image.SourceProperty, imgs.ConvertFromString(od.FileName.ToString()));
            fileName = od.FileName;
            if (!(Directory.Exists("PernanentEmpPhotos")))
                Directory.CreateDirectory("PernanentEmpPhotos");

            filePath = "PernanentEmpPhotos\\" + System.IO.Path.GetRandomFileName().Replace(".", "-") + System.IO.Path.GetExtension(od.FileName);
            File.Copy(od.FileName,filePath);
        }

        private void DisplayErrorMsg(uint ret)
        {
            MessageBox.Show(NBioAPI.Error.GetErrorDescription(ret) + " [" + ret.ToString() + "]", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        private void btnRegisterNew_Click(object sender, RoutedEventArgs e)
        {
            NBioAPI.Type.HFIR hNewFIR;
             uint nUserID;
             if (NavigateEmpNo == null)
             {
                 DataTable dt = AbhiruchiDAL.GetEmployeeMaxId();
                 if (dt.Rows[0][0].ToString() == "")
                 {
                     AbhiruchiDAL.resetSeed();
                     dt.Rows[0][0] = 1;
                 }
                 else
                     dt.Rows[0][0] = Convert.ToInt32(dt.Rows[0][0]) + 1;

                 nUserID = Convert.ToUInt32(dt.Rows[0][0]);
             }
             else
             {
                 DataTable dtId = AbhiruchiDAL.getEmployeeIdbasedOnEmployeeNo(NavigateEmpNo);
                 nUserID = Convert.ToUInt32(dtId.Rows[0][0]);
             }

            //// Get FIR data
            m_NBioAPI.OpenDevice(NBioAPI.Type.DEVICE_ID.AUTO);
            uint ret = m_NBioAPI.Enroll(out hNewFIR, null);
            if (ret != NBioAPI.Error.NONE)
            {
                DisplayErrorMsg(ret);
                m_NBioAPI.CloseDevice(NBioAPI.Type.DEVICE_ID.AUTO);
                return;
            }

            convertFIRInToBinary(hNewFIR);

            m_NBioAPI.CloseDevice(NBioAPI.Type.DEVICE_ID.AUTO);

            // Regist FIR to IndexSearch DB
            NBioAPI.IndexSearch.FP_INFO[] fpInfo;
            ret = m_IndexSearch.AddFIR(hNewFIR, nUserID, out fpInfo);
            if (ret != NBioAPI.Error.NONE)
            {
                DisplayErrorMsg(ret);
                return;
            }
            fingerPrintInfo = fpInfo;

        }

        private void convertFIRInToBinary(NBioAPI.Type.HFIR hNewFIR)
        {
            uint ret = NBioAPI.Error.NONE;
            NBioAPI.Type.FIR GetFirInfo;

            ret = m_NBioAPI.GetFIRFromHandle(hNewFIR, out GetFirInfo);


            if (ret == NBioAPI.Error.NONE)
            {
                fingerPrint = new MemoryStream();
                StreamWriter sw = new StreamWriter(fingerPrint);
                sw.Write(GetFirInfo);
                fingerData = new byte[GetFirInfo.Data.Length];
                fingerData = GetFirInfo.Data;
            }

            NBioAPI.Type.FIR_TEXTENCODE GetFirTextInfo;
            ret = m_NBioAPI.GetTextFIRFromHandle(hNewFIR, out GetFirTextInfo, true);
            if (ret == NBioAPI.Error.NONE)
            {
                string s = GetFirTextInfo.TextFIR.ToString();
                //MessageBox.Show(s.Length.ToString() );
                fingerPrintTextData = s;


            }

        }

        private NBioAPI.Type.FIR_TEXTENCODE convertFIRInToText(NBioAPI.Type.HFIR hNewFIR)
        {
            uint ret = NBioAPI.Error.NONE;
            NBioAPI.Type.FIR_TEXTENCODE GetFirTextInfo;
            ret = m_NBioAPI.GetTextFIRFromHandle(hNewFIR, out GetFirTextInfo, true);
            return GetFirTextInfo;

        }

        private void btnCompare_Click(object sender, RoutedEventArgs e)
        {
            NBioAPI.Type.HFIR hCapturedFIR;
            NBioAPI.Type.FIR_TEXTENCODE hMyCapturedFIR;
            NBioAPI.Type.FIR_TEXTENCODE hRegisterdFIR;

            m_NBioAPI.OpenDevice(NBioAPI.Type.DEVICE_ID.AUTO);
            uint ret = m_NBioAPI.Capture(out hCapturedFIR);
            if (ret != NBioAPI.Error.NONE)
            {
                DisplayErrorMsg(ret);
                m_NBioAPI.CloseDevice(NBioAPI.Type.DEVICE_ID.AUTO);
                return;
            }
            convertFIRInToBinary(hCapturedFIR);

            hMyCapturedFIR = new NBioAPI.Type.FIR_TEXTENCODE();
            hMyCapturedFIR = convertFIRInToText(hCapturedFIR);
            m_NBioAPI.CloseDevice(NBioAPI.Type.DEVICE_ID.AUTO);


            DataTable dtEmpBioMetric = new DataTable();
            dtEmpBioMetric = AbhiruchiDAL.getEmployeeBiometricInfo();

            hRegisterdFIR = new NBioAPI.Type.FIR_TEXTENCODE();

            NBioAPI.Type.FIR_PAYLOAD myPayload = new NBioAPI.Type.FIR_PAYLOAD();
            m_NBioAPI.OpenDevice(NBioAPI.Type.DEVICE_ID.AUTO);
            bool IsMatched = false;
            bool result;

            foreach (DataRow dr in dtEmpBioMetric.Rows)
            {


                hRegisterdFIR.TextFIR = dr[4].ToString();
                ret = m_NBioAPI.VerifyMatch(hMyCapturedFIR, hRegisterdFIR, out result, myPayload);
                if (ret != NBioAPI.Error.NONE)
                {
                    DisplayErrorMsg(ret);
                    return;
                }
                else
                {
                    if (result == true)
                    {
                        IsMatched = true;
                        MessageBox.Show("Welcome " + dr[5].ToString());
                        m_NBioAPI.CloseDevice(NBioAPI.Type.DEVICE_ID.AUTO);
                        return;
                    }
                }
            }
            if (IsMatched == false)
                MessageBox.Show("------ Sorry! Finger Print Not Matched-------");
            m_NBioAPI.CloseDevice(NBioAPI.Type.DEVICE_ID.AUTO);



        }

        private void btnClearImpressions_Click(object sender, RoutedEventArgs e)
        {
            fingerData = null;
            fingerPrintTextData = null;
            fingerPrintInfo = null;
        }

    }
}
